<template>
	<view class="container">
		<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem"
			styleType="text"></uni-segmented-control>
	    <view v-if="current === 0">
			<view  style="padding: 40rpx;">
				<!-- 基础用法，不包含校验规则 -->
				<uni-forms class="form" ref="baseForm" :modelValue="activeForm" label-position="left" labelWidth="100px">
					<uni-forms-item label="活动标题" required>
						<uni-easyinput v-model="activeForm.activityTitle" placeholder="请输入活动标题" />
					</uni-forms-item>
					<uni-forms-item label="活动执行人" required>
						<zxz-uni-data-select v-model="activeForm.teacherId" filterable :localdata="teacherList"
													@inputChange="inputChange" @change="change" />
					</uni-forms-item>
					<uni-forms-item label="执行日期" required>
						<uni-datetime-picker type="date" return-type="timestamp" v-model="activeForm.activityDate"/>
					</uni-forms-item>
					<uni-forms-item label="活动说明" required>
						<uni-easyinput type="textarea" v-model="activeForm.activityContent" placeholder="请输入活动说明" />
					</uni-forms-item>
					<uni-forms-item label="活动质量" required>
						<zxz-uni-data-select v-model="activeForm.activityQuality" filterable :localdata="qualities"
													@inputChange="inputChange" @change="change" />
					</uni-forms-item>
					<uni-forms-item label="活动照片" required>
						<uni-file-picker limit="9" v-model="photoList" @select="selectPhoto" @delete="delPhoto"/>
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="tijiao" @click="submitActivity">登 记</view>
		</view>
		<view v-if="current === 1">
			<uni-card style="padding-bottom: 20rpx;" v-for="(item,index) in activityList" :key="item.id" :title="item.activityTitle" :extra="item.activityDate">
				<uni-row>
					<uni-col :span="12">
						<view style="line-height: 35px; display: flex;">活动执行人：
						<view>{{item.username}}</view>
						</view>
					</uni-col>
					<uni-col :span="12">
						<view style="line-height: 35px; display: flex; ">活动质量：
						<view style="color: #fe0000;">{{item.activityLevel}}</view>
						</view>
					</uni-col>
				</uni-row>
				<uni-row>
					<uni-col :span="12">
						<view class="button" @click.stop="updateActivity(item)">修改</view>
					</uni-col>
					<uni-col :span="12">
						<view class="button" @click.stop="deleteActivity(item)">删除</view>
					</uni-col>
				</uni-row>
			</uni-card>
		</view>
	</view>
</template>

<script>
	import activity from '@/api/modules/activity'
	import { parseTime } from "@/utils/date.js"
	export default {
		data() {
			return {
				loginId: uni.getStorageSync("loginId"),
				activityQueryParams: {
								pageSize: 10,
								pageNum: 1
				},
				current: 0,
				items: ['活动登记', '已登记活动'],
				activeForm: {},
				photoList: [],
				qualities: [{
							"value": 1,
							"text": "正常",
						},
						{
							"value": 2,
							"text": "不展开"
						},
						{
							"value": 3,
							"text": "无质量展开"
						},
						],
				teacherList: []	,
				activityList: [],
				tempActivityList: []
			}
		},
		created() {
			activity.getClassTeacher().then(resp => {
				console.log(resp.data)
				if(resp.data !== null) {
					this.teacherList = [
						...resp.data.map(item => {
							let obj = {}
							obj.text = item.username
							obj.value = item.id
							return obj;
						})
					]
				}
				console.log(this.teacherList)
			})
		},
		onShow() {
			uni.showLoading({
				mask: true,
				title: '加载中...'
			});
			this.getSchoolActivity();
		},
		onReachBottom() {
			console.log('onReachBottom')
			if(this.current === 1) { 
				uni.showLoading({
					mask: true,
					title: '加载中...'
				});
				this.activityQueryParams.userId = this.loginId
				this.activityQueryParams.pageNum += 1
				activity.getActivityPageList(this.activityQueryParams).then(res => {
					uni.hideLoading()
					this.tempActivityList = res.data.list
					if(this.tempActivityList.length === 0) {
						this.activityQueryParams.pageNum -= 1
						uni.showToast({
							title: "没有更多数据...",
							icon: 'none',
						})
						return
					}
					this.tempActivityList.forEach(item => {
						item.activityDate = parseTime(item.activityDate)
						this.qualities.forEach(item1 => {
							if(item1.value === item.activityQuality) {
								item.activityLevel = item1.text
							}
						})
					})
					this.activityList = [...this.activityList, ...this.tempActivityList]
					
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err.message,
						icon: 'none',
					})
				})
			}
		},
		methods: {
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
				if (e.currentIndex == 1) {
					// 查询出已登记的活动
					uni.showLoading({
						mask: true,
						title: '加载中...'
					});
					this.getSchoolActivity();
				}
			},
			getSchoolActivity() {
				this.activityQueryParams.userId = this.loginId
				this.activityQueryParams.pageNum = 1
				activity.getActivityPageList(this.activityQueryParams).then(resp => {
					this.activityList = resp.data.list
					this.activityList.forEach(item => {
						item.activityDate = parseTime(item.activityDate)
						this.qualities.forEach(item1 => {
							if(item1.value === item.activityQuality) {
								item.activityLevel = item1.text
							}
						})
						
					})
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err.message,
						icon: 'none',
					})
				})
			},
			updateActivity(e) {
				console.log(e)
				// 跳转详情页
				uni.navigateTo({
					url: `/pages_duty/deptManager/activities/activityDetail?activityId=${e.id}`
				})
			},
			deleteActivity(e) {
				console.log(e)
				activity.deleteActivityById(e.id).then(resp => {
					if(resp.code === 200) {
						uni.showToast({
							title: "删除成功!",
							icon: 'none',
						})
						this.getSchoolActivity()
					}
				}).catch(err => {
					uni.showToast({
						title: err.data.message,
						icon: 'none',
					})
				})
			},
			inputChange(e) {
				console.log(e)
			},
			change(e) {
				console.log(e)
			},
			submitActivity() {
				console.log(this.activeForm)
				if (!this.activeForm.activityTitle) {
					uni.showToast({
						title: "请填写活动标题",
						icon: 'none',
					})
					return
				}
				if (!this.activeForm.teacherId) {
					uni.showToast({
						title: "请选择活动执行人",
						icon: 'none',
					})
					return
				}
				if (!this.activeForm.activityDate) {
					uni.showToast({
						title: "请选择执行日期",
						icon: 'none',
					})
					return
				}
				if (!this.activeForm.activityContent) {
					uni.showToast({
						title: "请输入活动说明",
						icon: 'none',
					})
					return
				}
				console.log(this.activeForm.activityQuality)
				if (!this.activeForm.activityQuality) {
					uni.showToast({
						title: "请选择活动质量",
						icon: 'none',
					})
					return
				}
				console.log(this.photoList.length)
				if (this.photoList.length === 0) {
					uni.showToast({
						title: "请选择活动照片",
						icon: 'none',
					})
					return
				}
				let photoUrlList = []
				this.photoList.forEach(item => {
					photoUrlList.push(item.url)
				})
				this.activeForm.photos = photoUrlList
				uni.showLoading({
					mask: true,
					title: '登记中'
				});
				// 提交活动
				activity.createOrUpdateActivity(this.activeForm).then(res => {
					this.reset()
					if (res.code == 200) {
						uni.hideLoading()
						uni.showToast({
							title: "活动登记成功",
							icon: 'none',
						})

					}
				}).catch(err => {
					this.reset()
					uni.hideLoading()
					uni.showToast({
						title: err.data.message,
						icon: 'none',
					})
				})
			},
			reset() {
				this.activeForm = {
					id: "",
					activityTitle: "",
					activityContent: "",
					activityDate: "",
					teacherName: "",
					activityQuality: "",
					photos: ""
				}
				
				this.photoList = []
			},
			selectPhoto(e) {
			   console.log('选择图片：', e)
			   e.tempFiles.forEach(tempFile => {
				   uni.uploadFile({
				     url: uni.url + 'classroom/hygiene/uploadHygienePhoto',
				     filePath: tempFile.url,
				     // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
				     name: 'file',
				     header: {
				       'Authorization': "Bearer " + uni.getStorageSync("token")
				     },
				     // 成功函数
				     success: (res) => {
						console.log('上传成功', res.data);
						var obj = JSON.parse(res.data);
						this.photoList.push({
							url: obj.data,
							extname: '',  
							uuid: tempFile.uuid 
						})
						console.log(this.photoList);
				     },
				     // 失败提示用户重新上传
				     fail: error => {
				       console.log('上传失败', error);
				     }
				    })
			   })
			 },
			 delPhoto(e) {
				 console.log("删除图片",e);
				 this.photoList = this.photoList.filter(item => item.url !== e.tempFile.url)
				 // if(e.tempFile.name !== '') {
					//  this.delPhotoIds.push(e.tempFile.name);
				 // }
				 
				 console.log(this.photoList)
			 },
		}
	}
</script>

<style>
.tijiao {
		z-index: 2;
		padding-bottom: 200px;
		flex-direction: column;
		position: fixed;
		bottom: 0;
		display: flex;
		width: 100%;
		background-color: #0000ff;
		padding: 20rpx;
		text-align: center;
		border-radius: 10rpx;
		color: #fff;
		font-size: 40rpx;
		box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
	}
	.button {
		width: 100%;
		background-color: #ffffff;
		color: #787878;
		/* padding: 20rpx; */
		border-radius: 10rpx;
		text-align: center;
		font-size: 30rpx;
		margin: 0 auto;
		border: 1px solid gray;
	}
</style>
